﻿using System;
using System.Runtime.InteropServices;

namespace Core.Experiment
{
    [StructLayout(LayoutKind.Explicit, Size = 4)]
    public struct UNum
    {
        [FieldOffset(0)]
        public byte b0;
        [FieldOffset(1)]
        public byte b1;
        [FieldOffset(2)]
        public byte b2;
        [FieldOffset(3)]
        public byte b3;

        [FieldOffset(0)]
        public int i;

        [FieldOffset(0)]
        public float f;
    }

    internal class Convert
    {
        private void TestConvertFloatToBytes()
        {
            //此方法会产生GC
            float f = 10;
            for (int i = 0; i < 1000; i++)
            {
                BitConverter.GetBytes(f);
            }
        }


        protected byte[] data;
        protected int dReader;

        private void TestConvertFloatToBytes_U()
        {
            //此方法不会产生GC
            float f = 10;
            for (int i = 0; i < 1000; i++)
            {
                var u = new UNum { f = f };
                data[dReader++] = u.b0;
                data[dReader++] = u.b1;
                data[dReader++] = u.b2;
                data[dReader++] = u.b3;
            }
        }
    }
}
